using System;
using System.Collections.Generic;



namespace Framework.Network
{
    public sealed partial class NetworkManager : FrameworkModule
    {
        private Dictionary<ushort, IMessageHandler> m_Opcode2Handler = new Dictionary<ushort, IMessageHandler>();

        public void InitDispatcher()
        {
            foreach (Type type in FrameworkEntry.GetTypes(typeof(MessageHandlerAttribute)))
            {
                IMessageHandler messageHandler = Activator.CreateInstance(type) as IMessageHandler;
                if (messageHandler == null)
                {
                    Log.Error($"message handle {type.Name} 需要继承 IMHandler");
					continue;
                }

                Type messageType = messageHandler.GetMessageType();
                ushort opcode = this.GetOpcode(messageType);
                if (opcode == 0)
                {
                    Log.Error($"消息opcode为0: {messageType.Name}");
					continue;
                }
                this.m_Opcode2Handler[opcode] = messageHandler;
            }
        }

        public void DispatcherMessage(Session session, ushort opcode, Object message)
        {
            IMessageHandler handler;
            if (!this.m_Opcode2Handler.TryGetValue(opcode, out handler))
            {
                Log.Error($"消息 {message.GetType().FullName} 没有处理");
				return;
            }
            try
            {
                handler.Handle(session, message);
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
    }
}